//
//  GRStoreViewController.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/8/24.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRStoreViewController.h"
#import "GRStoreGoodTableViewCell.h"
#import "GRStoreMsgTableViewCell.h"
#import "GRSotreCommentTableViewCell.h"
#import "GRStoreSectionHeaderView.h"
#import "GRStoreSectionFooterView.h"
#import "GRStoreHeaderView.h"
#import "GRGoodDetailPageVC.h"
#import "GRPayBillViewController.h"
#import "GRStoreAction.h"
#import "GRLocationManager.h"
#import "GRStoreDetailModel.h"
#import "GRNewsDetailViewController.h"
#import "GRShowMoreListVC.h"
#import "GRSubmitOrderVC.h"
#import "GRPhotoBrowserVC.h"
#import "GRTransitionAnimator.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <MapKit/MapKit.h>
@interface GRStoreViewController ()<UITableViewDelegate,UITableViewDataSource, GRStoreSectionFooterViewDelegate,GRStoreHeaderViewDelegate,GRStoreGoodTableViewCellDelegate,UINavigationControllerDelegate>
{
    NSInteger selectedIndex;
}
@property (weak, nonatomic) IBOutlet UITableView *storeList;
@property(nonatomic,strong)GRStoreHeaderView * headerView;
@property(nonatomic,strong)GRStoreDetailModel * storeDetailModel;
@property (weak, nonatomic) IBOutlet UIView *menuView;
@property(nonatomic,strong)NSMutableArray * cellArr;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property(nonatomic,strong)UIBarButtonItem * collectItem;

@end

@implementation GRStoreViewController

-(NSMutableArray *)cellArr{
    if(!_cellArr){
        _cellArr = [NSMutableArray array];
    }
    return _cellArr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self requestData];
    selectedIndex = 0;
    [self.storeList registerNib:[UINib nibWithNibName:@"GRStoreGoodTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"GRStoreGoodTableViewCell"];
    [self.storeList registerNib:[UINib nibWithNibName:@"GRStoreMsgTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"GRStoreMsgTableViewCell"];
    [self.storeList registerNib:[UINib nibWithNibName:@"GRSotreCommentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"GRSotreCommentTableViewCell"];
    self.headerView = [GRStoreHeaderView xx_instantiateFromNib];
    self.headerView.delegate = self;
}

-(void)LookBigPic:(NSInteger)index PhotoArr:(NSArray *)photoArr{
    GRPhotoBrowserVC * photoBrowser = [[GRPhotoBrowserVC alloc]init];
    photoBrowser.currentImageIndex = index;
    photoBrowser.imageArr = photoArr;
    self.navigationController.delegate = self;
    [self.navigationController pushViewController:photoBrowser animated:YES];
}

#pragma UINavigationDeleagte
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
    id <UIViewControllerAnimatedTransitioning> animationController;
    if ([toVC isKindOfClass:[GRPhotoBrowserVC class]]&& operation == UINavigationControllerOperationPush) {
        GRTransitionAnimator*  GRPushAnimation = [[GRTransitionAnimator alloc]init];
        GRPushAnimation.duration = 0.25;
        
        animationController =  GRPushAnimation;
        
    }else if([fromVC isKindOfClass:[GRPhotoBrowserVC class]] && operation == UINavigationControllerOperationPop ){
        GRTransitionAnimator*  GRPopAnimation = [[GRTransitionAnimator alloc]init];
        GRPopAnimation.duration = 0.25;
        animationController =  GRPopAnimation;
    }
    return animationController;
}



-(void)requestData{
    CLLocationCoordinate2D location =  [GRLocationManager defaultManager].coordinate;
     NSDictionary * dic = @{
                @"lantitude":@(location.latitude),
                @"longitude":@(location.longitude),
                @"profileId":[GRUserBasisInfo BasisID]
                };
    [GRStoreAction getStoreDetailWithStoreId:self.storeId ParamerDic:dic ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        NSLog(@"店铺详情%@",responseObject);
        if (success) {
            self.storeDetailModel = [GRStoreDetailModel yy_modelWithDictionary:responseObject];
//            [self setUpRightItem];

            self.headerView.nameLabel.text = self.storeDetailModel.nickname;
            self.headerView.moblie = self.storeDetailModel.mobile;
            self.headerView.scoreLable.text = [NSString stringWithFormat:@"%@丨评分:%.lf丨%@",self.storeDetailModel.name,[self.storeDetailModel.score floatValue],self.storeDetailModel.distance];
            self.headerView.storeName = self.storeDetailModel.nickname;
            self.headerView.griceLabel.text = [NSString stringWithFormat:@"享%.1f折优惠",self.storeDetailModel.pointGiveRate];
            self.headerView.timeLabel.text = [NSString stringWithFormat:@"营业时间:%@",self.storeDetailModel.bizTime];
            self.headerView.addressLabel.text = self.storeDetailModel.addr;
            self.headerView.photoArr = self.storeDetailModel.photosArray;
            self.headerView.coordinate =CLLocationCoordinate2DMake(self.storeDetailModel.latitude, self.storeDetailModel.longitude);
            
            NSMutableArray * menueArr = [NSMutableArray array];
      
            if ( self.storeDetailModel.discountList.count >0) {
                [self.cellArr addObject:@"GRStoreGoodTableViewCell"];
                [menueArr addObject:@"优惠"];
            }
            if (self.storeDetailModel.commentList.count >0) {
                  [self.cellArr addObject:@"GRSotreCommentTableViewCell"];
                 [menueArr addObject:@"评价"];
            }
            if (self.storeDetailModel.newsList.count >0 ) {
                 [self.cellArr addObject:@"GRStoreMsgTableViewCell"];
                [menueArr addObject:@"资讯"];
            }
            self.headerView.menueArr = menueArr;
            if (self.storeDetailModel.photosArray >0) {
                self.headerView.frame = CGRectMake(0, 0, KscreenWidth, 525);
            }else{
                self.headerView.frame = CGRectMake(0, 0, KscreenWidth, 422);
            }
            self.storeList.tableHeaderView = self.headerView;
            [self setMenueTitile:menueArr];
            [self.storeList reloadData];
        }else{
        }
    }];
}

-(void)setMenueTitile:(NSArray *)menueArr{
    for (int i = 0; i <menueArr.count; i++) {
        UIButton * button = [self.menuView viewWithTag:i+1000];
        [button setTitle:menueArr[i] forState:UIControlStateNormal];
        button.hidden = NO;
    }
}

-(void)setUpRightItem{
    UIBarButtonItem * shareItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"share_1"]  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStyleDone target:self action:@selector(shareStore)];
    UIBarButtonItem * collectItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:self.storeDetailModel.isFavorite?@"alreadyCollect_1": @"notCollect_1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(collectStore:)];

    self.navigationItem.rightBarButtonItems = @[shareItem,collectItem];
}

/**
 分享店铺
 */
-(void)shareStore{
    
  
    [[GRUMengCommon shareUMeng] sharePlatform:self title:self.storeDetailModel.nickname content:self.storeDetailModel.name image:self.storeDetailModel.shareImage webURL:nil miniApp:YES option:@{@"webpageUrl":(self.storeDetailModel.shareUrl?self.storeDetailModel.shareUrl:@""),@"userName":(self.storeDetailModel.originalId?self.storeDetailModel.originalId:@""),@"path":(self.storeDetailModel.appGoodsPage?self.storeDetailModel.appGoodsPage:@""),@"poster":self.storeDetailModel.shareImage}];

}

/**
 收藏店铺
 */
-(void)collectStore:(UIBarButtonItem*)item{
        [GRHUD showProgress:@"正在收藏"];
        [GRStoreAction addFavorite:self.storeDetailModel.id FavoriteType:@"shop" ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
            [GRHUD dismissHUD];
            if (success) {
                if ([responseObject boolValue]) {
                     [GRHUD showMessage:@"收藏成功"];
                        item.image = [[UIImage imageNamed:@"alreadyCollect_1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] ;
                }else{
                    [GRHUD showMessage:@"取消收藏"];
                    item.image = [[UIImage imageNamed:@"notCollect_1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] ;
                }
               
            }else{
            [GRHUD showMessage:@"收藏失败"];
            }
        }];
}

#pragma  mark - UItableViewDelegate、UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * identifer = self.cellArr[indexPath.section];
    if ([identifer isEqualToString:@"GRStoreGoodTableViewCell"] ) {
        GRStoreGoodTableViewCell * goodCell = [tableView dequeueReusableCellWithIdentifier:@"GRStoreGoodTableViewCell" forIndexPath:indexPath];
        goodCell.delegate = self;
       goodCell.discountGoodModel = self.storeDetailModel.discountList[indexPath.row];
        
        return goodCell;
    }else if([identifer isEqualToString:@"GRSotreCommentTableViewCell"]){
        GRSotreCommentTableViewCell * commentCell = [tableView dequeueReusableCellWithIdentifier:@"GRSotreCommentTableViewCell" forIndexPath:indexPath];
        commentCell.commentModel = self.storeDetailModel.commentList[indexPath.row];
        return commentCell;
    }else{
        GRStoreMsgTableViewCell * storeMsgCell = [tableView dequeueReusableCellWithIdentifier:@"GRStoreMsgTableViewCell" forIndexPath:indexPath];
        storeMsgCell.newsModel = self.storeDetailModel.newsList[indexPath.row];
        return storeMsgCell;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return self.cellArr.count;
    return 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
      NSString * identifer = self.cellArr[section];
    if ([identifer isEqualToString:@"GRStoreGoodTableViewCell"] ) {
        return self.storeDetailModel.discountList.count;
    }else if ([identifer isEqualToString:@"GRSotreCommentTableViewCell"]){
      return self.storeDetailModel.commentList.count;
       
    }else{
       return self.storeDetailModel.newsList.count;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    GRStoreSectionFooterView * footView = [GRStoreSectionFooterView xx_instantiateFromNib];
    footView.section = section;
    footView.delegate = self;
    return footView;
}
-(void)lookMoreAction:(NSInteger)section{
    GRShowMoreListVC * moreListVC = [[GRShowMoreListVC alloc]init];
    NSString * identifer = self.cellArr[section];
    if ([identifer isEqualToString:@"GRStoreGoodTableViewCell"] ) {

        moreListVC.listType = ShowMoreListTypeDiscountGood;
       }else if ([identifer isEqualToString:@"GRSotreCommentTableViewCell"]){
       moreListVC.listType = ShowMoreListTypeComment;
    }else{
         moreListVC.listType = ShowMoreListTypeNews;
    }
    moreListVC.isStore = YES;
    moreListVC.listId = self.storeId;
    [self.navigationController pushViewController:moreListVC animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSString * identifer = self.cellArr[section];
    GRStoreSectionHeaderView * headerView = [GRStoreSectionHeaderView xx_instantiateFromNib];
    if ([identifer isEqualToString:@"GRSotreCommentTableViewCell"]){
        headerView.titleLabel.text = @"用户评价";
        
        headerView.isComment = YES;
        headerView.commentNumLabel.text = [NSString stringWithFormat:@"(%ld）",self.storeDetailModel.commentNum];
        headerView.percentLabel.text = [NSString stringWithFormat:@"%ld%%好评率",self.storeDetailModel.commentRate];
    }else if([identifer isEqualToString:@"GRStoreMsgTableViewCell"]){
        headerView.titleLabel.text = @"热门资讯";
    }
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        NSString * identifer = self.cellArr[indexPath.section];
    if ([identifer isEqualToString:@"GRStoreGoodTableViewCell"] ) {
        GRDiscountGoodModel * goodModel = self.storeDetailModel.discountList[indexPath.row];
        return [goodModel cellHeight];
    }else if ([identifer isEqualToString:@"GRSotreCommentTableViewCell"]){
        GRStoreCommentModel * commentModel = self.storeDetailModel.commentList[indexPath.row];
        return [commentModel cellHeight];
    }else{
        GRNewsModel * newModel = self.storeDetailModel.newsList[indexPath.row];
        return [newModel cellHeight];
    }

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * identifer = self.cellArr[indexPath.section];
    if ([identifer isEqualToString:@"GRStoreGoodTableViewCell"] ) {
        GRGoodDetailPageVC * goodDetailPageVC = [[ GRGoodDetailPageVC alloc]init];
        [self.navigationController pushViewController:goodDetailPageVC animated:YES];
        GRDiscountGoodModel * goodModel = self.storeDetailModel.discountList[indexPath.row];
        goodDetailPageVC.goodId = goodModel.id;
    }else if ([identifer isEqualToString:@"GRSotreCommentTableViewCell"]){
        
    }else{
        GRNewsDetailViewController * newsDetailVC = [[GRNewsDetailViewController alloc]init];
        GRNewsModel * newsModel = self.storeDetailModel.newsList[indexPath.row];
        newsDetailVC.title = newsModel.title;
        newsDetailVC.type = newsModel.type;
        newsDetailVC.newsId = newsModel.id;
        [self.navigationController pushViewController:newsDetailVC animated:YES];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (scrollView.contentOffset.y <=416) {
//        self.menuView.hidden = YES;
//    }else{
//        self.menuView.hidden = NO;
//
//    }
}

- (IBAction)payOrderAction:(id)sender {
    if ([GRUserBasisInfo isLogin]) {
        GRPayBillViewController * payBillVC = [[GRPayBillViewController alloc]init];
        payBillVC.storeId = self.storeId;
        payBillVC.isValid = YES;
        [self.navigationController pushViewController:payBillVC animated:YES];
    }else{
        [self goToLogin];
    }
   
}


- (IBAction)seletedMenue:(UIButton *)sender {
    [self ScrollerToIndex:sender.tag -1000];
    
}

-(void)ScrollerToIndex:(NSInteger)index{
   
    UIButton * selectedBtOne = [self.menuView viewWithTag:selectedIndex+1000];
    selectedBtOne.selected = NO;
    UIButton * selectedTwo =[self.headerView viewWithTag:selectedIndex+1000];
    selectedTwo.selected = NO;
    UIButton * selectedBtThree = [self.menuView viewWithTag:index+1000];
    selectedBtThree.selected = YES;
    UIButton * selectedFour =[self.headerView viewWithTag:index+1000];
    selectedFour.selected = YES;
    [UIView animateWithDuration:0.25 animations:^{
        self.lineView.centerX = selectedBtThree.center.x;
        self.headerView.lineView.centerX = selectedFour.center.x;
    }];
    selectedIndex = index;
    [self.storeList scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
}

-(void)purchaseAction:(NSInteger)goodId{
    GRSubmitOrderVC * submitOrderId = [[GRSubmitOrderVC alloc]init];
    submitOrderId.goodId = goodId;
    [self.navigationController pushViewController:submitOrderId animated:YES];
}

-(void)openNavi{
    [self tunedUpMapOfLocation:CLLocationCoordinate2DMake(self.storeDetailModel.latitude, self.storeDetailModel.longitude) AtPoiName:self.storeDetailModel.addr];
}

- (void)tunedUpMapOfLocation:(CLLocationCoordinate2D)coordinate AtPoiName:(NSString *)poiName {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *ownMapAction = [UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MKMapItem *startItem = [MKMapItem mapItemForCurrentLocation];
        
        MKMapItem *toItem = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
        toItem.name = poiName;
        
        NSArray *items = [NSArray arrayWithObjects:startItem, toItem, nil];
        
        
        NSDictionary *option = @{MKLaunchOptionsDirectionsModeKey:
                                     MKLaunchOptionsDirectionsModeDriving,
                                 MKLaunchOptionsMapTypeKey: [NSNumber numberWithInteger:MKMapTypeStandard],
                                 MKLaunchOptionsShowsTrafficKey:@YES};
        
        [MKMapItem openMapsWithItems:items launchOptions:option];
    }];
    
    UIAlertAction *amapAction = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        // 导航
            NSString *url = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=龟米&backScheme=applicationScheme&lat=%lf&lon=%lf&dev=0&style=0", coordinate.latitude,coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        
        [self adjustThirdMap:url];
        
    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
 
    
    [alertController addAction:ownMapAction];
    [alertController addAction:amapAction];

    [alertController addAction:cancleAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

// 调起第三方地图
- (void)adjustThirdMap:(NSString *)urlstr {
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlstr]]) {
        [NSObject openSystemURL:urlstr];
    }else {
        [[LFAlertBox  defaultAlert] showAlert:@"未安装此应用，无法打开进行导航!" completion:nil];

    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
